"use client";
import React, { useState, useEffect } from "react";
import {
  Layout,
  Menu,
  Button,
  Table,
  message,
  Modal,
  Form,
  Input,
  Select,
  List,
  Pagination,
  Card,
} from "antd";
import {
  UserOutlined,
  FileTextOutlined,
  FlagOutlined,
  AppstoreOutlined,
  LogoutOutlined,
  PlusOutlined,
  LikeOutlined,
  CommentOutlined,
  StarOutlined,
} from "@ant-design/icons";
import { useRouter } from "next/navigation";
import { useUser } from "../context/userContext";
import api from "../utils/api";
import "antd/dist/reset.css";

const { Header, Sider, Content } = Layout;
const { Option } = Select;

// 封装错误处理函数
const handleError = (error, messageText) => {
  console.error(messageText, error);
  if (error.response && error.response.status === 403) {
    message.error("无权限操作");
  } else {
    message.error("网络请求失败，请检查网络连接");
  }
};

export default function AdminManagementPage() {
  const [selectedKey, setSelectedKey] = useState("1");
  const [pendingPosts, setPendingPosts] = useState([]);
  const [totalPendingPosts, setTotalPendingPosts] = useState(0);
  const [users, setUsers] = useState([]);
  const [totalUsers, setTotalUsers] = useState(0);
  const [categories, setCategories] = useState([]);
  const [createCategoryModalVisible, setCreateCategoryModalVisible] =
    useState(false);
  const [updateCategoryModalVisible, setUpdateCategoryModalVisible] =
    useState(false);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [reports, setReports] = useState([]);
  const [resolveReportModalVisible, setResolveReportModalVisible] =
    useState(false);
  const [selectedReport, setSelectedReport] = useState(null);
  const router = useRouter();
  const { user } = useUser();
  const accessToken = user ? user.access_token : "";

  // 创建表单实例
  const [createCategoryForm] = Form.useForm();
  const [updateCategoryForm] = Form.useForm();
  const [resolveReportForm] = Form.useForm();

  // 新增：动态控制Sider折叠状态
  const [collapsed, setCollapsed] = useState(false);

  // 新增：分页相关状态
  const [pendingPostsPage, setPendingPostsPage] = useState(1);
  const [pendingPostsPageSize, setPendingPostsPageSize] = useState(5);
  const [usersPage, setUsersPage] = useState(1);
  const [usersPageSize, setUsersPageSize] = useState(5);
  const [reportsPage, setReportsPage] = useState(1);
  const [reportsPageSize, setReportsPageSize] = useState(5);

  // 新增帖子展示相关状态
  const [postCategories, setPostCategories] = useState([]);
  const [postList, setPostList] = useState([]);
  const [postTotal, setPostTotal] = useState(0);
  const [postPage, setPostPage] = useState(1);
  const [postPageSize] = useState(4);
  const [currentPostCategory, setCurrentPostCategory] = useState("all");

  // 新增置顶相关状态和处理函数
  const handlePinPost = async (postId) => {
    try {
      const response = await api.put(
        "http://120.26.138.4:3000/posts/pin",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (response.status === 200) {
        message.success("帖子置顶成功！");
        // 重新获取帖子列表
        await fetchPostsList(currentPostCategory, postPage);
      }
    } catch (error) {
      handleError(error, "置顶帖子出错");
    }
  };

  const handleUnpinPost = async (postId) => {
    try {
      const response = await api.put(
        "http://120.26.138.4:3000/posts/unpin",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (response.status === 200) {
        message.success("取消置顶成功！");
        // 重新获取帖子列表
        await fetchPostsList(currentPostCategory, postPage);
      }
    } catch (error) {
      handleError(error, "取消置顶出错");
    }
  };

  const handleMenuClick = (e) => {
    setSelectedKey(e.key);
    if (e.key === "3") {
      fetchReports(reportsPage, reportsPageSize);
    } else if (e.key === "5") {
      fetchPostCategories();
      setPostPage(1);
      setCurrentPostCategory("all");
    }
  };

  const handleLogout = () => {
    router.push("/");
  };

  const handleSwitchToUser = () => {
    router.push("/homepage/home");
  };

  const fetchPosts = async (page = 1, pageSize = 10) => {
    try {
      const response = await api.get("http://120.26.138.4:3000/posts/pending", {
        params: { page, pageSize },
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      const postData = response.data || { posts: [], total: 0 };
      if (!Array.isArray(postData.posts)) {
        console.error("待审核帖子数据格式错误，posts 不是数组:", postData);
        throw new Error("待审核帖子数据格式错误，posts 不是数组");
      }
      setPendingPosts(postData.posts || []);
      setTotalPendingPosts(postData.total || 0);
    } catch (error) {
      handleError(error, "获取待审核帖子数据失败");
    }
  };

  const fetchUsers = async (page = 1, limit = 10) => {
    if (!accessToken) {
      message.error("请先登录");
      return;
    }
    try {
      const response = await api.get("http://120.26.138.4:3000/users/all", {
        params: { page, limit },
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (!response.data || !Array.isArray(response.data.uers)) {
        console.error("用户数据格式错误，uers 不是数组:", response.data);
        throw new Error("用户数据格式错误，uers 不是数组");
      }
      setUsers(response.data.uers || []);
      setTotalUsers(response.data.total || 0);
    } catch (error) {
      handleError(error, "获取用户信息失败");
    }
  };

  const fetchCategories = async () => {
    try {
      const response = await api.get(
        "http://120.26.138.4:3000/categories/all",
        {
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (!response.data || !Array.isArray(response.data.Reponse)) {
        console.error("分区数据格式错误，Reponse 不是数组:", response.data);
        throw new Error("分区数据格式错误，Reponse 不是数组");
      }
      setCategories(response.data.Reponse);
    } catch (error) {
      handleError(error, "获取分区信息失败");
    }
  };

  const fetchReports = async (page = 1, pageSize = 10) => {
    try {
      const response = await api.get("http://120.26.138.4:3000/reports/list", {
        params: { page, pageSize },
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (!response.data || !Array.isArray(response.data.Report)) {
        console.error("举报列表数据格式错误，Report 不是数组:", response.data);
        throw new Error("举报列表数据格式错误，Report 不是数组");
      }
      setReports(response.data.Report);
    } catch (error) {
      handleError(error, "获取举报列表失败");
    }
  };

  // 新增获取帖子分类
  const fetchPostCategories = async () => {
    try {
      const response = await api.get(
        "http://120.26.138.4:3000/categories/all",
        {
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (response.data && Array.isArray(response.data.Reponse)) {
        setPostCategories(response.data.Reponse);
      }
    } catch (error) {
      handleError(error, "获取帖子分类失败");
    }
  };

  // 新增获取帖子列表
  const fetchPostsList = async (category = "all", page = 1) => {
    try {
      let url = "http://120.26.138.4:3000/posts/list";
      let params = { page, pageSize: postPageSize };

      if (category !== "all") {
        url = "http://120.26.138.4:3000/posts/category";
        params = { ...params, categoryId: category };
      }

      const response = await api.get(url, {
        params,
        headers: { Authorization: `Bearer ${accessToken}` },
      });

      if (response.data && Array.isArray(response.data.posts)) {
        const postsWithAuthor = await Promise.all(
          response.data.posts.map(async (post) => {
            try {
              const userResponse = await api.get(
                "http://120.26.138.4:3000/users/info",
                {
                  params: { id: post.authorId },
                }
              );
              const pinnedStatus = post.isPinned || false;
              return {
                ...post,
                authorDisplayName:
                  userResponse.data?.display_name || "未知作者",
                isPinned: pinnedStatus,
              };
            } catch (error) {
              return {
                ...post,
                authorDisplayName: "未知作者",
                isPinned: false,
              };
            }
          })
        );

        setPostList(postsWithAuthor);
        setPostTotal(response.data.total || 0);
      }
    } catch (error) {
      handleError(error, "获取帖子列表失败");
    }
  };

  useEffect(() => {
    if (selectedKey === "5") {
      fetchPostsList(currentPostCategory, postPage);
    }
    fetchPosts(pendingPostsPage, pendingPostsPageSize);
    fetchUsers(usersPage, usersPageSize);
    fetchCategories();
  }, [
    selectedKey,
    pendingPostsPage,
    pendingPostsPageSize,
    usersPage,
    usersPageSize,
    currentPostCategory,
    postPage,
  ]);
  const [rejectModalVisible, setRejectModalVisible] = useState(false);
  const [rejectMessage, setRejectMessage] = useState("");
  const [currentRejectPost, setCurrentRejectPost] = useState({});
  const handleApprovePost = async (postId, authorId) => {
    try {
      // 发送审核通过请求
      const approveResponse = await api.put(
        "http://120.26.138.4:3000/posts/approve",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );

      if (approveResponse.status === 200) {
        // 发送审核通过提醒
        await sendAlert("你的帖子已通过", authorId);
        message.success("帖子审核通过并已发送通知");
        await fetchPosts(pendingPostsPage, pendingPostsPageSize);
      }
    } catch (error) {
      handleError(error, "审核通过处理出错");
    }
  };

  const handleOpenRejectModal = (postId, authorId) => {
    setRejectModalVisible(true);
    setCurrentRejectPost({ id: postId, authorId });
  };

  const handleRejectPost = async () => {
    try {
      const { id: postId, authorId } = currentRejectPost;

      // 发送审核拒绝请求
      const rejectResponse = await api.put(
        "http://120.26.138.4:3000/posts/reject",
        {},
        {
          params: { id: postId },
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );

      if (rejectResponse.status === 200 && rejectMessage.trim()) {
        // 发送自定义拒绝提醒
        await sendAlert(rejectMessage.trim(), authorId);
        message.success("帖子审核拒绝并已发送通知");
        await fetchPosts(pendingPostsPage, pendingPostsPageSize);
        setRejectModalVisible(false);
      }
    } catch (error) {
      handleError(error, "审核拒绝处理出错");
    }
  };
  const sendAlert = async (message, receiverId) => {
    try {
      const response = await api.post(
        "/alerts",
        { message, receiver_id: receiverId },
        {
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );
      if (!response.data.success) {
        throw new Error("提醒发送失败");
      }
    } catch (error) {
      handleError(error, "提醒发送失败");
      message.error("通知发送失败，但审核操作已完成");
    }
  };
  const handleBanUser = async (userId) => {
    try {
      const response = await api.post(
        `http://120.26.138.4:3000/users/ban?id=${userId}`,
        undefined,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );
      if (response.status === 201) {
        message.success("用户封禁成功！");
        await fetchUsers(usersPage, usersPageSize);
      }
    } catch (error) {
      handleError(error, "封禁用户出错");
    }
  };

  const handleUnbanUser = async (userId) => {
    try {
      const response = await api.post(
        `http://120.26.138.4:3000/users/unban?id=${userId}`,
        undefined,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );
      if (response.status === 201) {
        message.success("用户解封成功！");
        await fetchUsers(usersPage, usersPageSize);
      }
    } catch (error) {
      handleError(error, "解封用户出错");
    }
  };

  const handleCreateCategory = async (values) => {
    try {
      const requestData = {
        id: parseInt(values.id),
        name: values.name,
        description: values.description,
      };
      console.log("创建分区请求数据:", requestData);
      const response = await api.post(
        "http://120.26.138.4:3000/categories/create",
        requestData,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );
      console.log("创建分区响应数据:", response.data);
      if (response.status === 201) {
        message.success("分区创建成功！");
        setCreateCategoryModalVisible(false);
        await fetchCategories();
      }
    } catch (error) {
      handleError(error, "创建分区出错");
    }
  };

  const handleUpdateCategory = async (values) => {
    try {
      const requestData = {
        id: selectedCategory.id,
        name: values.name,
        description: values.description,
      };
      const response = await api.put(
        "http://120.26.138.4:3000/categories/update",
        requestData,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
            "Content-Type": "application/json",
          },
        }
      );
      if (response.status === 200) {
        message.success("分区更新成功！");
        setUpdateCategoryModalVisible(false);
        await fetchCategories();
      }
    } catch (error) {
      handleError(error, "更新分区出错");
    }
  };

  const handleDeleteCategory = async (categoryId) => {
    try {
      const response = await api.delete(
        `http://120.26.138.4:3000/categories/delete?id=${categoryId}`,
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        }
      );
      if (response.status === 200) {
        message.success("分区删除成功！");
        await fetchCategories();
      }
    } catch (error) {
      handleError(error, "删除分区出错");
    }
  };

  const postColumns = [
    { title: "ID", dataIndex: "id", key: "id" },
    { title: "内容标题", dataIndex: "title", key: "title" },
    { title: "作者", dataIndex: "authorId", key: "authorId" },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: () => "待审核",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          <Button type="primary" onClick={() => handleApprovePost(record.id)}>
            通过审核
          </Button>
          <Button
            type="primary"
            danger
            style={{ marginLeft: 8 }}
            onClick={() => handleRejectPost(record.id)}
          >
            拒绝审核
          </Button>
        </div>
      ),
    },
  ];

  const userColumns = [
    { title: "ID", dataIndex: "uid", key: "uid" },
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "邮箱", dataIndex: "email", key: "email" },
    { title: "角色", dataIndex: "role", key: "role" },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        return status === "active" ? "正常" : "封禁";
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          <Button type="primary" onClick={() => handleBanUser(record.uid)}>
            封禁
          </Button>
          <Button
            type="primary"
            danger
            style={{ marginLeft: 8 }}
            onClick={() => handleUnbanUser(record.uid)}
          >
            解封
          </Button>
        </div>
      ),
    },
  ];

  const categoryColumns = [
    { title: "ID", dataIndex: "id", key: "id" },
    { title: "名称", dataIndex: "name", key: "name" },
    { title: "描述", dataIndex: "description", key: "description" },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          <Button
            type="primary"
            onClick={() => {
              setSelectedCategory(record);
              setUpdateCategoryModalVisible(true);
            }}
          >
            更新
          </Button>
          <Button
            type="primary"
            danger
            style={{ marginLeft: 8 }}
            onClick={() => handleDeleteCategory(record.id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  const reportColumns = [
    { title: "举报ID", dataIndex: "id", key: "id" },
    { title: "举报理由", dataIndex: "reason", key: "reason" },
    { title: "举报类型", dataIndex: "type", key: "type" },
    { title: "被举报项ID", dataIndex: "reportedItemId", key: "reportedItemId" },
    { title: "状态", dataIndex: "status", key: "status" },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Button
          type="primary"
          onClick={() => {
            setSelectedReport(record);
            setResolveReportModalVisible(true);
          }}
        >
          处理
        </Button>
      ),
    },
  ];

  const userPagination = {
    current: usersPage,
    pageSize: usersPageSize,
    total: totalUsers,
    onChange: (page, pageSize) => {
      setUsersPage(page);
      setUsersPageSize(pageSize);
      fetchUsers(page, pageSize);
    },
  };

  const postPagination = {
    current: pendingPostsPage,
    pageSize: pendingPostsPageSize,
    total: totalPendingPosts,
    onChange: (page, pageSize) => {
      setPendingPostsPage(page);
      setPendingPostsPageSize(pageSize);
      fetchPosts(page, pageSize);
    },
  };

  const reportPagination = {
    current: reportsPage,
    pageSize: reportsPageSize,
    total: reports.length,
    onChange: (page, pageSize) => {
      setReportsPage(page);
      setReportsPageSize(pageSize);
      fetchReports(page, pageSize);
    },
  };

  const renderContent = () => {
    switch (selectedKey) {
      case "1":
        return (
          <Table
            columns={userColumns}
            dataSource={users}
            pagination={userPagination}
          />
        );
      case "2":
        return (
          <Table
            columns={postColumns}
            dataSource={pendingPosts}
            pagination={postPagination}
          />
        );
      case "3":
        return (
          <Table
            columns={reportColumns}
            dataSource={reports}
            pagination={reportPagination}
          />
        );
      case "4":
        return (
          <div>
            <Button
              type="primary"
              onClick={() => setCreateCategoryModalVisible(true)}
            >
              创建分区
            </Button>
            <Table
              columns={categoryColumns}
              dataSource={categories}
              pagination={false}
            />
          </div>
        );
      case "5":
        return (
          <div>
            <Menu
              mode="horizontal"
              selectedKeys={[currentPostCategory]}
              style={{ borderBottom: "1px solid #e8e8e8", marginBottom: 20 }}
              itemIconRender={() => null}
              selectable
              onSelect={({ key }) => {
                setCurrentPostCategory(key);
                setPostPage(1);
              }}
            >
              <Menu.Item key="all">全部</Menu.Item>
              {postCategories.map((category) => (
                <Menu.Item key={category.id}>{category.name}</Menu.Item>
              ))}
            </Menu>

            <List
              itemLayout="vertical"
              dataSource={postList}
              renderItem={(item) => (
                <Card style={{ cursor: "pointer", marginBottom: "10px" }}>
                  <Card.Meta
                    title={item.title}
                    description={`作者：${item.authorDisplayName}`}
                  />
                  <div style={{ marginTop: "10px" }}>{item.content}</div>

                  {/* 新增置顶操作按钮 */}
                  <div
                    style={{
                      marginTop: 16,
                      display: "flex",
                      justifyContent: "flex-end",
                    }}
                  >
                    <Button
                      type="primary"
                      onClick={() => handlePinPost(item.id)}
                    >
                      置顶帖子
                    </Button>
                    <Button
                      type="primary"
                      danger
                      onClick={() => handleUnpinPost(item.id)}
                    >
                      取消置顶
                    </Button>
                  </div>
                </Card>
              )}
            />

            <div
              style={{
                display: "flex",
                justifyContent: "center",
                marginTop: 20,
              }}
            >
              <Pagination
                current={postPage}
                pageSize={postPageSize}
                total={postTotal}
                onChange={(newPage) => setPostPage(newPage)}
              />
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider
        breakpoint="lg"
        collapsedWidth="0"
        onBreakpoint={(broken) => {
          console.log(broken);
        }}
        onCollapse={(newCollapsed) => setCollapsed(newCollapsed)}
        style={{
          backgroundColor: "#f0f2f5",
          position: "fixed",
          height: "100vh",
          overflowY: "auto",
        }}
      >
        <div className="logo" />
        <Menu
          mode="inline"
          selectedKeys={[selectedKey]}
          onClick={handleMenuClick}
          style={{ backgroundColor: "#f0f2f5" }}
          items={[
            {
              key: "1",
              icon: <UserOutlined />,
              label: "用户管理",
            },
            {
              key: "2",
              icon: <FileTextOutlined />,
              label: "审核帖子",
            },
            {
              key: "3",
              icon: <FlagOutlined />,
              label: "处理举报",
            },
            {
              key: "4",
              icon: <AppstoreOutlined />,
              label: "分区管理",
            },
            {
              key: "5",
              icon: <FileTextOutlined />,
              label: "帖子置顶管理",
            },
            {
              key: "6",
              icon: <LogoutOutlined />,
              label: (
                <Button type="link" onClick={handleLogout}>
                  退出
                </Button>
              ),
            },
            {
              key: "7",
              label: (
                <Button type="link" onClick={handleSwitchToUser}>
                  切换为用户
                </Button>
              ),
            },
          ]}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: 0,
            background: "#fff",
          }}
        />
        <Content
          style={{
            margin: `24px 16px 24px ${collapsed ? 80 : 256}px`,
            padding: 24,
            background: "#fff",
            minHeight: 280,
            overflowY: "auto",
          }}
        >
          {renderContent()}
        </Content>
      </Layout>
      <Modal
        title="创建分区"
        visible={createCategoryModalVisible}
        onOk={() => {
          createCategoryForm
            .validateFields()
            .then((values) => {
              handleCreateCategory(values);
            })
            .catch((errorInfo) => {
              console.log("表单验证失败:", errorInfo);
            });
        }}
        onCancel={() => setCreateCategoryModalVisible(false)}
      >
        <Form form={createCategoryForm} id="create-category-form">
          <Form.Item
            label="ID"
            name="id"
            rules={[{ required: true, message: "请输入分区ID" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: "请输入分区名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="更新分区"
        visible={updateCategoryModalVisible}
        onOk={() => {
          updateCategoryForm
            .validateFields()
            .then((values) => {
              handleUpdateCategory(values);
            })
            .catch((errorInfo) => {
              console.log("表单验证失败:", errorInfo);
            });
        }}
        onCancel={() => setUpdateCategoryModalVisible(false)}
      >
        <Form
          form={updateCategoryForm}
          id="update-category-form"
          initialValues={selectedCategory}
        >
          <Form.Item
            label="名称"
            name="name"
            rules={[{ required: true, message: "请输入分区名称" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="description">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="审核拒绝"
        visible={rejectModalVisible}
        onOk={handleRejectPost}
        onCancel={() => setRejectModalVisible(false)}
      >
        <Form>
          <Form.Item
            label="拒绝原因"
            rules={[{ required: true, message: "请填写拒绝原因" }]}
          >
            <Input.TextArea
              rows={3}
              value={rejectMessage}
              onChange={(e) => setRejectMessage(e.target.value)}
              placeholder="请输入给作者的拒绝理由（必填）"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
}
